/*
 * PanelLevelSelector.java
 *
 * Created on 24 December 2007, 13:30
 *
 * Copyright (C) 2007-2008  Hylke van der Schaaf
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, in version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package hextd.UI;

import hextd.HexTD;
import hextd.util.Context;
import hextd.util.MapIO;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Vector;
import javax.swing.DefaultListModel;
import javax.swing.ListModel;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;

/**
 *
 * @author  hylke
 */
public class PanelLevelSelector extends javax.swing.JPanel {

    private Context context;
    private HexTD mainApp;
    private Vector<String[]> levels;
    private DefaultListModel model;
    private URL indexUrl;
    private HTMLEditorKit editorkit;

    /** Creates new form PanelLevelSelector */
    public PanelLevelSelector() {
        this.setVisible(false);
        this.model = new DefaultListModel();
        this.levels = new Vector<String[]>();
        this.editorkit = new HTMLEditorKit();
    }

    public void setContext(Context c, HexTD mainApp) {
        this.context = c;
        this.mainApp = mainApp;

        initComponents();

        StyleSheet s = this.context.loadStyleSheet("styles.css");
        this.editorkit.setStyleSheet(s);
        this.jTextPane_levelInfo.setEditorKit(this.editorkit);
    }

    private void refillList() {
        for (Iterator<String[]> i = this.levels.iterator(); i.hasNext();) {
            String[] level = i.next();
            this.model.addElement(level[0]);
        }
        this.jList1.setSelectedIndex(0);
    }

    private void selectLevel(int i) {
        if (i >= 0 && i < this.levels.size()) {
            String[] levelInfo = this.levels.get(i);
            URL fetchUrl;
            try {
                fetchUrl = new URL(this.indexUrl, levelInfo[1]);
                context.loadMap(fetchUrl, levelInfo[1]);
            } catch (MalformedURLException ex) {
                ex.printStackTrace();
            }
        }
    }

    public void loadIndex(String fileUrl) {
        URL fetchUrl;
        BufferedReader bufferedreader;
        this.levels.clear();

        try {
            fetchUrl = new URL(this.context.contextUrl, fileUrl);
            this.indexUrl = fetchUrl;
            //System.out.println("PanelLevelSelector::FetchFromUrl::file = " + fetchUrl.toString());
            URLConnection urlconnection = fetchUrl.openConnection();
            if (urlconnection.getContentEncoding() != null) {
                bufferedreader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(), urlconnection.getContentEncoding()));
            } else {
                bufferedreader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(), "utf-8"));
            }
        } catch (IOException _ex) {
            System.err.println("HexTD::readFile:: Can't read from " + fileUrl);
            return;
        }

        this.context.mapContextUrl = this.indexUrl;

        String sLine1, sLine2;
        try {
            while ((sLine1 = bufferedreader.readLine()) != null) {
                if (sLine1.trim().length() != 0) {
                    if ((sLine2 = bufferedreader.readLine()) != null) {
                        if (sLine2.trim().length() != 0) {
                            String[] levelInfo = {sLine1, sLine2};
                            this.levels.add(levelInfo);
                        }
                    }
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        this.refillList();
    }

    private void loadNew() {
        BufferedReader b = new BufferedReader(new StringReader(this.jTextPane1.getText()));
        this.context.loadMap(b, "Custom");
        this.mainApp.mapChanged();
    }

    public void setLevelInfo(String html) {
        this.jTextPane_levelInfo.setText(html);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jFrame1 = new javax.swing.JFrame();
        jPanel1 = new javax.swing.JPanel();
        jButton_cancel = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();
        jButton_load = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jButton_start = new javax.swing.JButton();
        jButton_new = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTextPane_levelInfo = new javax.swing.JTextPane();

        jFrame1.setBackground(new java.awt.Color(0, 0, 0));
        jFrame1.setMinimumSize(new java.awt.Dimension(600, 400));

        jPanel1.setBackground(new java.awt.Color(0, 0, 0));
        jPanel1.setForeground(new java.awt.Color(220, 255, 220));
        jPanel1.setLayout(new java.awt.GridBagLayout());

        jButton_cancel.setBackground(new java.awt.Color(0, 0, 0));
        jButton_cancel.setForeground(new java.awt.Color(220, 255, 220));
        jButton_cancel.setText("Cancel");
        jButton_cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_cancelActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHWEST;
        jPanel1.add(jButton_cancel, gridBagConstraints);

        jLabel1.setBackground(new java.awt.Color(0, 0, 0));
        jLabel1.setForeground(new java.awt.Color(220, 255, 220));
        jLabel1.setText("Paste the level definition in the box and click \"Load\".");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = 2;
        jPanel1.add(jLabel1, gridBagConstraints);

        jScrollPane2.setViewportView(jTextPane1);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 0.01;
        gridBagConstraints.weighty = 0.01;
        jPanel1.add(jScrollPane2, gridBagConstraints);

        jButton_load.setBackground(new java.awt.Color(0, 0, 0));
        jButton_load.setForeground(new java.awt.Color(220, 255, 220));
        jButton_load.setText("Load");
        jButton_load.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_loadActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHEAST;
        jPanel1.add(jButton_load, gridBagConstraints);

        jFrame1.getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        setBackground(context.colors.getColorBackGround());
        setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Select Level", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Bitstream Vera Sans", 0, 13), context.colors.getColorForeGround()));
        setForeground(context.colors.getColorForeGround());
        setMaximumSize(new java.awt.Dimension(200, 2147483647));
        setMinimumSize(new java.awt.Dimension(200, 25));
        setPreferredSize(new java.awt.Dimension(200, 139));
        setLayout(new java.awt.GridBagLayout());

        jScrollPane1.setBackground(context.colors.getColorBackGround());
        jScrollPane1.setForeground(context.colors.getColorForeGround());

        jList1.setBackground(context.colors.getColorBackGround());
        jList1.setForeground(context.colors.getColorForeGround());
        jList1.setModel(this.model);
        jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jList1ValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jList1);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0E-4;
        gridBagConstraints.weighty = 0.1;
        add(jScrollPane1, gridBagConstraints);

        jButton_start.setBackground(context.colors.getColorBackGround());
        jButton_start.setForeground(context.colors.getColorForeGround());
        jButton_start.setText("Start!");
        jButton_start.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_startActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 0.01;
        add(jButton_start, gridBagConstraints);

        jButton_new.setBackground(context.colors.getColorBackGround());
        jButton_new.setForeground(context.colors.getColorForeGround());
        jButton_new.setText("Load");
        jButton_new.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_newActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 0.01;
        add(jButton_new, gridBagConstraints);

        jPanel2.setBackground(context.colors.getColorBackGround());
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Level Info", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Bitstream Vera Sans", 0, 13), context.colors.getColorForeGround()));
        jPanel2.setForeground(context.colors.getColorForeGround());
        jPanel2.setLayout(new java.awt.BorderLayout());

        jScrollPane3.setBorder(null);

        jTextPane_levelInfo.setBorder(null);
        jScrollPane3.setViewportView(jTextPane_levelInfo);

        jPanel2.add(jScrollPane3, java.awt.BorderLayout.CENTER);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0E-4;
        gridBagConstraints.weighty = 0.05;
        add(jPanel2, gridBagConstraints);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton_loadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_loadActionPerformed
        this.loadNew();
        this.jFrame1.setVisible(false);
    }//GEN-LAST:event_jButton_loadActionPerformed

    private void jButton_cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_cancelActionPerformed
        this.jFrame1.setVisible(false);
    }//GEN-LAST:event_jButton_cancelActionPerformed

    private void jButton_newActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_newActionPerformed
        this.jFrame1.pack();
        this.jFrame1.setVisible(true);
    }//GEN-LAST:event_jButton_newActionPerformed

    private void jButton_startActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_startActionPerformed
        this.mainApp.startLevel();
    }//GEN-LAST:event_jButton_startActionPerformed

    private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jList1ValueChanged
        this.selectLevel(this.jList1.getSelectedIndex());
    }//GEN-LAST:event_jList1ValueChanged
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton_cancel;
    private javax.swing.JButton jButton_load;
    private javax.swing.JButton jButton_new;
    private javax.swing.JButton jButton_start;
    private javax.swing.JFrame jFrame1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JList jList1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextPane jTextPane1;
    private javax.swing.JTextPane jTextPane_levelInfo;
    // End of variables declaration//GEN-END:variables
}
